import { Component, OnInit } from '@angular/core';
import { RandomUserService } from '../../../home/randomUser.service';
import { NzMessageService } from 'ng-zorro-antd';
import { getFakeChartData } from '../../../../../../_mock/chart.service';
import { _HttpClient } from '@core/services/http.client';
import { HttpClient, HttpParams } from '@angular/common/http';
import { getRule, saveRule, removeRule } from '../../../../../../_mock/rule.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpService } from '@core/services/http.service';
import { ActivatedRoute, Router } from '@angular/router';
import { FileUploader } from 'ng2-file-upload';
import { DomSanitizer } from '@angular/platform-browser';
import swal, { SweetAlertType } from 'sweetalert2';

declare var jsPlumb: any;
const URL = 'https://139.196.189.173:8089/VisualizationMgt/fileUp/uploadFile';

@Component({
    selector: 'app-flow',
    templateUrl: './flow.component.html',
    styleUrls: ['./flow.component.less'],
    styles: [`
        :host ::ng-deep .vertical-center-modal {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        :host ::ng-deep .vertical-center-modal .ant-modal {
            top: 100px;
        }
    `]
})
export class FlowComponent implements OnInit {
    q: any = {
        pi: 1,
        ps: 10,
        sorter: '',
        status: -1,
        statusList: []
    };

    type = 0;

    currNode;
    list = new Array<Node>()
    rightSrc;
    gourpModalVisible = false;

    roleShow = false;

    fileChange($event) {

        this.file = $event.target.files[0];
        // this.rightData.text = this.file.name;
    }

    onBlur() {
        for (const data of this.nids) {
            if (data.value === this.currNode.id) {
                data.label = this.currNode.text;
            }
        }
    }

    // fileChange($event) {
    //     const file: File = $event.target.files[0];
    //     const myReader: FileReader = new FileReader();
    //     const that = this;
    //     myReader.onloadend = (loadEvent: any) => {
    //         this.currNode.props.group_img = loadEvent.target.result;
    //         that.rightSrc = loadEvent.target.result;
    //         // const img = new Image();
    //
    //         // img.src = loadEvent.target.result;
    //         // img.onload = function() {
    //         //     that.rightStyleW = this['width'];
    //         //     that.rightStyleH = this['height'];
    //         // };
    //     };
    //     myReader.readAsDataURL(file);
    // }

    editNode(i, ev?, g_id?) {
        if (ev) {
            ev.stopPropagation();
        }
        this.insertFlag = false
        this.modalVisible = true
        this.currNode = i;
        this.currNode.group_id = g_id;


    }

    _checked
    data: any[] = [];
    loading = false;
    selectedRows: any[] = [];
    curRows: any[] = [];
    totalCallNo = 0;
    allChecked = false;
    indeterminate = false;
    gids = [
        { label: '默认分组', value: '-1' },

    ];
    ntypes = [
        { text: '默认', value: 'process', type: 'default' },
        { text: '逻辑分支', value: 'fork', type: 'default' },
        { text: '开始', value: 'start', type: 'default' },
        { text: '结束', value: 'end', type: 'default' },
        { text: '空节点', value: 'empty', type: 'default' },
        { text: '准备分组', value: 'grouping', type: 'default' }


    ];
    gtypes = [
        { text: '默认', value: 'default', type: 'default' },
        { text: '固定人数', value: 'fixed', type: 'default' },
        { text: '百分比', value: 'percent', type: 'default' },
        { text: '剩余', value: 'remain', type: 'default' }
    ];
    status = [
        { text: '关闭', value: false, type: 'default' },
        { text: '运行中', value: false, type: 'processing' },
        { text: '已上线', value: false, type: 'success' },
        { text: '异常', value: false, type: 'error' }
    ];
    sortMap: any = {};
    expandForm = false;
    modalVisible = false;
    description = '';
    insertFlag = false;

    role = JSON.parse(localStorage.getItem('_user')).role;
    tempgnode;
    copy(gid, ev?) {
        const g_id = gid
        console.log(gid)
        if (ev) {
            ev.stopPropagation()
        }

    }

    addEl(gid, ev?) {
        if (ev) {
            ev.stopPropagation()
        }

        this.insertFlag = true
        this.modalVisible = true
        this.insertModel = new Node();
        this.insertModel.group_id = gid
        this.insertModel.id = this.getId();
        this.insertModel.visibleGroup.push(gid)
    }

    insertModel = new Node();

    dis = false;
    process(argu?) {
        this.border = false;
        this.list.length = 1;
        this.roleShow = false;
        if (argu === 'dis') {
            this.dis = true;
        } else {
            this.dis = false;
        }
    }
    border = false;
    insert(gid?, ev?, role?) {

        if (gid && ev) {
            this.insertFlag = true
            this.modalVisible = false
            this.insertModel = new Node();
            this.insertModel.group_id = gid
            this.insertModel.id = this.getId();
            this.insertModel.visibleGroup.push(gid);
            this.insertModel.text = '新增节点';
        } else {
            this.insertFlag = true
            this.modalVisible = false
            this.insertModel = new Node();
            this.insertModel.group_id = '-1'
            this.insertModel.id = this.getId();
            this.insertModel.type = 'group'
            this.insertModel.props = new Props();
            this.dis = false;
            if (role) {
                this.border = true;
                this.roleShow = true
            } else {
                this.border = false;
                this.roleShow = false;
            }
            if (this.list.length > 1) {
                return false;
            }
        }

        if (this.insertModel.group_id != '-1') {
            for (let s of this.list) {
                if (s.id == this.insertModel.group_id) {
                    s.nodes.push(this.insertModel);
                }
            }
        } else {
            this.list.push(this.insertModel)
        }


        this.modalVisible = false;
        this.updateGids();
        this.updateNodes();
        this.getData();
    }

    addGroup() {

        this.insertFlag = true
        this.modalVisible = true
        this.insertModel = new Node();
        this.insertModel.group_id = '-1'
        this.insertModel.id = this.getId();
        this.insertModel.type = 'group'
        this.insertModel.props = new Props();
    }

    p_data;
    come_list;

    gotoScenceEditor(i?, g_id?) {

        if (i && g_id) {
            this.insertFlag = false;
            this.currNode = i;
            this.currNode.group_id = g_id;
        }


        this.getData()
        let tempnids = new Array();
        for (let nid of this.nids) {
            for (let nodeid of this.currNode.node_id) {
                if (nodeid == nid.value) {
                    tempnids.push(nid);
                }
            }
        }
        let data = {
            n_id: this.currNode.id,
            g_id: this.currNode.group_id,
            n_name: this.currNode.text,
            g_name: this.currNode.props.group_text,
            node_id: this.currNode.node_id,
            nids: tempnids,
            p_id: this.p_id,
            p_data: this.p_data,
            gids: this.gids,
            p_width: this.p_width,
            p_height: this.p_height,
            come_list: this.currNode.visibleGroup,
            typename: this.typename
        }

        if (this.currNode.type == 'empty') {
            data.come_list = []
        }
        this.router.navigate(['xiangmu/full/scene/edit'],
            {
                queryParams: {
                    data: JSON.stringify(data) + ""
                },
                skipLocationChange: true
            })
    }

    validateForm: FormGroup;
    nids = [];
    files: any[] = [];

    ngAfterViewInit() {


    }


    file

    savePdf() {
        const formData: FormData = new FormData();
        formData.append('uploadFile', this.file);
        formData.append('Type', 'Image');
        this.httpClient.post(this.Http.BASE_URL + '/fileUp/uploadFile', formData).subscribe(res => {
            if (res['code'] === '0') {
                // swal(`${res['msg']}`, '', 'info');
                this.rightSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.Http.IP_PORT + res['filepath']);
                if (this.currNode) {
                    this.currNode.props.group_img = res['filepath']
                }
                if (this.insertModel) {
                    this.insertModel.props.group_img = res['filepath']
                }
            }
        });
    }

    updateGids() {
        this.gids = new Array()
        this.gids.push({ label: '默认分组', value: '-1' })
        for (let s of this.list) {
            if (s.type == 'group') {
                this.gids.push({ label: s.props.group_text, value: s.id })
            }

        }
    }

    updateNodes() {
        this.nids = new Array()
        for (let d of this.list) {
            if (d.type == 'group') {
                for (let s of d.nodes) {
                    this.nids.push({ value: s.id, label: s.text });
                }
            } else {
                this.nids.push({ value: d.id, label: d.text });
            }

            // nzShowSearch
        }
    }

    constructor(public sanitizer: DomSanitizer, private Http: HttpService, public msg: NzMessageService, public httpClient: HttpClient, private http: _HttpClient, private fb: FormBuilder, public router: Router, public route: ActivatedRoute) {
    }

    getData() {


        let p = { p_id: this.p_id, processs: this.list, isCloud: this.typename };
        this.Http.saveFlow(p).subscribe(v => {
            if (v['code'] === '0') {
                // swal(`${v['msg']}`, '', 'info');
            }
        });
    }

    p_id;
    p_width;
    p_height;
    typename;

    ngOnInit() {

        this.route.queryParams.subscribe(res => {
            this.typename = res['type_name'];
            console.log(res);
            this.router.navigate([res.process_type], {
                relativeTo: this.route, queryParams: { p_id: res['p_id'], p_width: res['p_width'], p_height: res['p_height'], process_type: res['process_type'], type_name: res['type_name'] }
                // skipLocationChange: true
            })

            this.p_id = res['p_id']
            this.p_width = res['p_width']
            this.p_height = res['p_height']
            let p;
            // if (this.role == 3) {
            p = { p_id: this.p_id, isCloud: res['type_name'] };
            // } else {
            // p = { p_id: this.p_id, isCloud: 'true' };
            // }

            this.Http.getProjProcess(p).subscribe(res => {

                // this.list=res;
                if (res['list'].length > 0) {
                    this.list = JSON.parse(res['list'][0]['p_data'])
                    this.updateGids();
                    this.updateNodes();
                } else {
                    this.insertFlag = true
                    this.modalVisible = false
                    this.insertModel = new Node();
                    this.insertModel.group_id = '-1'
                    this.insertModel.id = this.getId();
                    this.insertModel.type = 'group'
                    this.insertModel.props = new Props();
                    this.list.push(this.insertModel);
                    this.updateGids();
                    this.updateNodes();
                    //this.getData();
                }
            });
        });

        this.validateForm = this.fb.group({
            s1: [null, [Validators.email]],
            s2: [null, [Validators.email]],
            s3: [null, [Validators.email]],
            s4: [null, [Validators.email]],
            s5: [null, [Validators.email]],
            s6: [null, [Validators.email]],
            s7: [null, [Validators.email]],
            s46: [null, [Validators.email]],
            s67: [null, [Validators.email]],
            s678: [null, [Validators.email]]

        });
    }

    getId() {
        return new Date().getTime() + "";
    }


    add() {
        this.modalVisible = true;
        this.description = '';
    }

    save() {

        this.loading = true;
        saveRule(this.description);
        this.getData();
        setTimeout(() => this.modalVisible = false, 500);
    }

    remove() {
        this.selectedRows.forEach(i => removeRule(i.no));
        this.getData();
        this.clear();
    }

    approval() {
        this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
    }

    clear() {
        this.selectedRows = [];
        this.totalCallNo = 0;
        this.data.forEach(i => i.checked = false);
        this.refreshStatus();
    }

    checkAll(value: boolean) {
        this.curRows.forEach(i => {
            if (!i.disabled) i.checked = value;
        });
        this.refreshStatus();
    }

    refreshStatus() {
        const allChecked = this.curRows.every(value => value.disabled || value.checked);
        const allUnChecked = this.curRows.every(value => value.disabled || !value.checked);
        this.allChecked = allChecked;
        this.indeterminate = (!allChecked) && (!allUnChecked);
        this.selectedRows = this.data.filter(value => value.checked);
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.callNo, 0);
    }

    getIndexInGroup(groupid) {
        let arr;
        for (let g of this.list) {
            if (g.id == groupid) {
                arr = g.nodes
            }
        }
        return arr.indexOf(this.currNode)
    }

    left(groupid) {
        let i = this.getIndexInGroup(groupid)
        if (i == 0) {
            return
        }
        this.swapItem(groupid, i, i - 1);

    }

    right(groupid) {
        let i = this.getIndexInGroup(groupid)
        let arr;
        for (let g of this.list) {
            if (g.id == groupid) {
                arr = g.nodes
            }
        }

        if (i == arr.length - 1) {
            return
        }
        this.swapItem(groupid, i, i + 1);
    }

    swapItem(groupid, i, j) {
        let arr;
        for (let g of this.list) {
            if (g.id == groupid) {
                arr = g.nodes
            }
        }
        if (arr) {
            arr[i] = arr.splice(j, 1, arr[i])[0]
            return arr;
        }
    }

    deleteNode(i?, g_id?) {

        if (i && g_id) {
            this.currNode = i;
            this.currNode.group_id = g_id;
        }

        this.getData()
        this.modalVisible = false;

        for (let d of this.list) {
            if (d.id == this.currNode.id) {
                let index = this.list.indexOf(d, 0);
                if (index > -1) {
                    this.list.splice(index, 1);
                }
            }

            if (d.type == 'group') {
                for (let s of d.nodes) {
                    if (s.id == this.currNode.id) {
                        let index = d.nodes.indexOf(s);
                        if (index > -1) {
                            d.nodes.splice(index, 1);
                        }
                    }
                }
            }

        }
        this.updateGids();
        this.updateNodes();
    }

    sort(field: string, value: any) {
        this.sortMap = {};
        this.sortMap[field] = value;
        this.q.sorter = value ? `${field}_${value}` : '';
        this.getData();
    }

    dataChange(res: any) {
        this.curRows = res;
        this.refreshStatus();
    }

    pageChange(pi: number): Promise<any> {
        this.q.pi = pi;
        this.loading = true;
        return new Promise((resolve) => {
            setTimeout(() => {
                this.loading = false;
                resolve();
            }, 500);
        });
    }

    reset(ls: any[]) {
        for (const item of ls) item.value = false;
        this.getData();
    }

    showSave() {
        swal('保存成功！', '', 'success');
    }

    groups = 2;
    groupSave() {

        for (let i = 0; i < this.groups - this.list.length; i++) {
            this.insertFlag = true
            this.modalVisible = false
            this.insertModel = new Node();
            this.insertModel.group_id = '-1'
            this.insertModel.id = this.getId();
            this.insertModel.type = 'group'
            this.insertModel.props = new Props();
            this.dis = false;
            this.list.push(this.insertModel)
            this.modalVisible = false;
            this.updateGids();
            this.updateNodes()
            this.getData();
        }
        this.gourpModalVisible = false;

    }
    groupModal() {
        this.gourpModalVisible = true;
    }
}

export class Node {
    public id;
    public type;
    public text;
    public group_id;
    public visibleGroup = new Array
    public node_id = new Array<string>();
    public nodes = new Array<Node>();
    public style = new Style();
    public props = new Props();
}

export class Style {

}

export class Props {
    public group_text
    public group_img
    public group_type
    public group_limit
}
